package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;


/**
 *  该线程任务负责与指定客户端完成HTTP交互
 *  与客户端交流的流程分成三步:
 *  1.:解析请求
 *  2:处理请求
 *  3:发送响应
 */
public class ClientHandler implements Runnable{
    private Socket socket ;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        //读取客户端发过来的消息
        try {
            //1 解析请求
            //1.1解析请求行
            String line= readLine();
            System.out.println(line);

            //请求行相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议版本
            String[] s = line.split(" ");
            method = s[0];
            uri = s[1];//这里可能会出现数组下标越界异常!原因:浏览器空请求，后期会解决
            protocol = s[2];
            //http://localhost:8088/index.html
            System.out.println("method:"+method); //GET
            System.out.println("uri:"+uri);       // /index.html
            System.out.println("protocol:"+protocol); //HTTP/1.1

            //1.2 解析消息头
            Map<String,String> headers = new HashMap<>();

//            while (!(line=readLine()).isEmpty()){
//                System.out.println("消息头:"+line);
//            }
            while (true) {
                line = readLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println("消息头:"+line);
                String[] str = line.split(":\\s");
                headers.put(str[0],str[1]);
            }
            System.out.println("headers:"+headers);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 通过socket获取的输入流读取客户端发送过来的一行字符串
     * @return
     */
    private String readLine() throws IOException{
        InputStream in = socket.getInputStream();
        int d ;
        char pre = 'a' , cur = 'a';
        StringBuilder sb = new StringBuilder();
        while ((d =in.read())!=-1){
            cur = (char)d;;
            if (pre==13&&cur ==10){
                break;
            }
            sb.append(cur);
            pre = cur ;
        }
        return   sb.toString().trim();
    }
}
